import matplotlib.pyplot as plt


# 读取日志文件
def read_log_file(log_file):
    epochs = []
    losses = []
    accuracies = []

    with open(log_file, 'r') as f:
        for line in f:
            if 'Epoch' in line and 'Loss' in line and 'Accuracy' in line:
                parts = line.strip().split(', ')
                epoch = int(parts[0].split()[1])
                loss = float(parts[1].split()[1])
                accuracy = float(parts[2].split()[1])
                epochs.append(epoch)
                losses.append(loss)
                accuracies.append(accuracy)

    return epochs, losses, accuracies


log_file = "training_log.txt"
log_file1 = "training_log1.txt"
epochs, losses, accuracies = read_log_file(log_file)
epochs1, losses1, accuracies1 = read_log_file(log_file1)


def plot_results(accuracies, accuracies1, epochs):
    fig, ax1 = plt.subplots()

    ax1.set_xlabel('Epoch')
    ax1.set_ylabel('Accuracy', color='tab:red')
    ax1.plot(epochs, accuracies, color='tab:red', label='Accuracy')
    ax1.tick_params(axis='y', labelcolor='tab:red')

    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    ax2.set_ylabel('Accuracy1', color='tab:blue')  # we already handled the x-label with ax1
    ax2.plot(epochs, accuracies1, color='tab:blue', label='Accuracy1')
    ax2.tick_params(axis='y', labelcolor='tab:blue')

    fig.tight_layout()  # otherwise the right y-label is slightly clipped
    plt.title('Training and Accuracy')
    plt.show()


# 示例用法
plot_results(accuracies, accuracies1, epochs)
